document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const authForm = document.getElementById('authForm');
    const submitButton = document.getElementById('submitButton');
    const switchMode = document.getElementById('switchMode');
    const switchText = document.getElementById('switchText');
    const errorMessage = document.getElementById('errorMessage');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');

    // 当前模式（登录/注册）
    let isLogin = true;

    // 切换登录/注册模式
    switchMode.addEventListener('click', function() {
        isLogin = !isLogin;
        submitButton.textContent = isLogin ? getLocalizedString('login') : getLocalizedString('register');
        switchText.textContent = isLogin ? getLocalizedString('no_account') : getLocalizedString('have_account');
        switchMode.textContent = isLogin ? getLocalizedString('register') : getLocalizedString('login');
        hideError();
    });

    // 表单提交处理
    authForm.addEventListener('submit', function(e) {
        e.preventDefault();
        hideError();

        const username = usernameInput.value.trim();
        const password = passwordInput.value.trim();

        // 基本验证
        if (!username || !password) {
            showError(getLocalizedString('user_required'));
            return;
        }

        if (username.length < 3) {
            showError(getLocalizedString('username_short'));
            return;
        }

        if (password.length < 6) {
            showError(getLocalizedString('password_short'));
            return;
        }

        if (isLogin) {
            handleLogin(username, password);
        } else {
            handleRegister(username, password);
        }
    });

    // 处理登录
    function handleLogin(username, password) {
        // 从localStorage获取用户数据
        const users = JSON.parse(localStorage.getItem('users') || '{}');
        
        // 检查用户是否存在
        if (!users[username]) {
            showError(getLocalizedString('user_not_exist'));
            return;
        }

        // 验证密码
        if (users[username].password !== password) {
            showError(getLocalizedString('wrong_password'));
            return;
        }

        // 登录成功
        loginSuccess(username);
    }

    // 处理注册
    function handleRegister(username, password) {
        // 从localStorage获取用户数据
        const users = JSON.parse(localStorage.getItem('users') || '{}');
        
        // 检查用户是否已存在
        if (users[username]) {
            showError(getLocalizedString('user_exists'));
            return;
        }

        // 创建新用户
        users[username] = {
            username: username,
            password: password,
            createdAt: new Date().toISOString()
        };

        // 保存用户数据
        localStorage.setItem('users', JSON.stringify(users));

        // 注册成功后自动登录
        loginSuccess(username);
    }

    // 登录成功处理
    function loginSuccess(username) {
        // 保存当前用户信息
        const currentUser = {
            username: username,
            loginTime: new Date().toISOString()
        };
        localStorage.setItem('currentUser', JSON.stringify(currentUser));

        // 跳转到聊天页面
        window.location.href = 'chat.html';
    }

    // 显示错误信息
    function showError(message) {
        errorMessage.textContent = message;
        errorMessage.style.display = 'block';
    }

    // 隐藏错误信息
    function hideError() {
        errorMessage.style.display = 'none';
    }

    // 检查是否已登录
    const currentUser = localStorage.getItem('currentUser');
    if (currentUser) {
        // 已登录，跳转到聊天页面
        window.location.href = 'chat.html';
    }
});